import { _decorator, Color, Component, instantiate, Label, Node, Prefab, Tween, tween, Vec3 } from 'cc';
import EventMgr from '../new/event/EventMgr';
import { EventId } from '../new/event/EventId';
import { BattleRoleUI } from './roleUI/BattleRoleUI';
import { BattleRole } from '../new/role/BattleRole';
import { BattleManager } from '../new/BattleManager';
import { BattleState } from '../new/common/BattleState';
import { DamageResult, ITriggerResult } from '../new/trigger/const/ITriggerResult';
import { DamageAction } from './UITrigger/actions/DamageAction';
import { SkillData } from '../new/skill/const/SkillData';
import { UITriggerType } from './UITrigger/UITriggerType';
import { WalkToTarget } from './UITrigger/actions/WalkToTarget';
import { AttackAction } from './UITrigger/actions/AttackAction';
import { SkillBase } from '../new/skill/SkillBase';
import { GoBack } from './UITrigger/actions/GoBack';
import { ActionQueue } from './action/ActionQueue';
import { BuffDamageAction } from './UITrigger/actions/BuffDamageAction';
import { UseSkill } from './UITrigger/actions/UseSkill';
import { CreateEffect } from './UITrigger/actions/CreateEffect';
import { AttackEnd } from './UITrigger/actions/AttackEnd';
import { TreateAction } from './UITrigger/actions/TreateAction';
const { ccclass, property } = _decorator;

@ccclass('BattleScene')
export class BattleScene extends Component {
    @property(Node)
    NodeLayer: Node;
    @property(Node)
    UILayer: Node;
    @property(Node)
    SkillPanel: Node;
    @property(Node)
    ResultPanel: Node;
    @property(Prefab)
    floatTxtPrefab: Prefab;
    private roleDic: {}
    private _curRoleUI: BattleRoleUI

    private actionQueue: ActionQueue;//玩家走近目标/施法动作-攻击-反击-回到原位

    start() {
        EventMgr.ins.on(EventId.ADD_ROLES, this.addRoles, this);
        EventMgr.ins.on(EventId.ADD_ROLE, this.addRole, this);
        EventMgr.ins.on(EventId.BATTLE_STATE_UI, this.battleState, this);
        EventMgr.ins.on(EventId.CREATE_SKILL_ACTION, this.createSkillAction, this);
        EventMgr.ins.on(EventId.TRIGGER_RESULT, this.onTriggerResult, this);
        EventMgr.ins.on(EventId.DO_SHOW_SKILL, this.doShowSkill, this);
        EventMgr.ins.on(EventId.FLOAT_TXT, this.floatTxt, this);
        EventMgr.ins.on(EventId.ADD_SKILL_EFFECT, this.addSkillEffect, this);


        this.roleDic = {};
        this.SkillPanel.active = false;
        this.ResultPanel.active = false;
        this.actionQueue = new ActionQueue();
        BattleManager.ins.init();
    }

    update(deltaTime: number) {

    }

    battleState(state: BattleState): void {
        switch (state) {
            case BattleState.ROLE_ACTION://对行动角色做一些表现处理，高亮之类的
                this.onRoleAction()
                break;
            case BattleState.ROLE_ACTION_END://对行动角色做一些表现处理，高亮之类的
                this.onRoleActionEnd()
                break;
            case BattleState.SELECT_SKILL:
                this.onSelectSkill();
                break
            case BattleState.SELECT_TARGET:
                this.onSelectTarget();
                break;
            case BattleState.USE_SKILL:
                this.onUseSkill();
                break;
        }
    }

    /**角色行动-对行动角色做一些表现处理，高亮之类的-然后打开行动角色的技能选择（选技能，然后选目标，就触发释放技能） */
    onRoleAction(): void {
        if (this._curRoleUI) {
            this._curRoleUI.actionEnd();
        }
        let role = BattleManager.ins.curRole;
        this._curRoleUI = this.roleDic[role.uid];
        if (!role || !this._curRoleUI) return;
        this._curRoleUI.action();
        // if (role.roleData.group == "self") {
        //触发回合开始buff效果
        this._curRoleUI.UITriggerMgr.trigger(UITriggerType.actionStart_ui);
        EventMgr.ins.event(EventId.BATTLE_STATE, BattleState.SELECT_SKILL);
        // }
    }

    onRoleActionEnd(): void {
        // let role = BattleManager.ins.curRole;
        // let roleUI: BattleRoleUI = this.roleDic[role.uid];
        // if (!role || !roleUI) return;
        // roleUI.actionEnd();
        // if (role.roleData.group == "self") {
        // }
    }

    onSelectSkill(): void {
        this.SkillPanel.active = true;
    }

    onSelectTarget(): void {
        this.SkillPanel.active = false;
    }

    onUseSkill(): void {
        this.SkillPanel.active = false;
        //注册使用技能行动
    }

    /**做技能表现 */
    doShowSkill(casters: BattleRole[]): void {
        let casterUI: BattleRoleUI = this.roleDic[casters[0].uid];
        console.log("触发beforeAttack_ui行为")
        casterUI.UITriggerMgr.trigger(UITriggerType.beforeAttack_ui)
    }

    /**创建释放技能的表现(近战走到目标，远程创建子弹特效) */
    createSkillAction(args: any) {
        let caster: BattleRole = args[0];
        let targets: BattleRole[] = args[1]
        let skill: SkillBase = args[2]
        let casterUI: BattleRoleUI = this.roleDic[caster.uid];
        let targetUI: BattleRoleUI = this.roleDic[targets[0].uid];
        if (skill.skillData.attackDic == -1) {//远程
            // casterUI.UITriggerMgr.registerTrigger(UITriggerType.beforeAttack_ui, new UseSkill(casterUI))
            casterUI.UITriggerMgr.registerTrigger(UITriggerType.beforeAttack_ui, new UseSkill(casterUI))
            if (skill.skillData.skillEffect) {
                casterUI.UITriggerMgr.registerTrigger(UITriggerType.beforeAttack_ui, new CreateEffect(casterUI, targetUI, skill.skillData))
            }
            casterUI.UITriggerMgr.registerTrigger(UITriggerType.attackEnd_ui, new AttackEnd())
        } else {//近战(走到目标目前)
            console.log("创建走到目标目前行为")
            casterUI.UITriggerMgr.registerTrigger(UITriggerType.beforeAttack_ui, new WalkToTarget(casterUI, targetUI, skill.skillData.attackDic))
            console.log("创建回到出生地行为")
            casterUI.UITriggerMgr.registerTrigger(UITriggerType.attackEnd_ui, new GoBack(casterUI))
        }

        //创建攻击行为
        console.log("创建攻击行为")
        casterUI.UITriggerMgr.registerTrigger(UITriggerType.attack_ui, new AttackAction(casterUI, skill.skillData.animation))
    }

    /**针对一个目标的结果 */
    onTriggerResult(result: any) {
        console.log("创建伤害行为0")
        if (result.resultType == "attackDamage") {
            console.log("创建伤害行为")
            let casterUI: BattleRoleUI = this.roleDic[result.caster.uid];
            let targetUI: BattleRoleUI = this.roleDic[result.target.uid];
            casterUI.UITriggerMgr.registerTrigger(UITriggerType.atkDamage_ui, new DamageAction(casterUI, targetUI, result))
        } else if (result.resultType == "buffDamage") {
            console.log("创建buff伤害行为")
            let targetUI: BattleRoleUI = this.roleDic[result.target.uid];
            targetUI.UITriggerMgr.registerTrigger(UITriggerType.actionStart_ui, new BuffDamageAction(targetUI, result))
        } else if (result.resultType == "treate") {
            console.log("创建回血行为")
            let targetUI: BattleRoleUI = this.roleDic[result.target.uid];
            targetUI.UITriggerMgr.registerTrigger(UITriggerType.atkDamage_ui, new TreateAction(targetUI, result))
        }
    }

    addRoles(battleRoles: BattleRole[]): void {
        for (let i = 0; i < battleRoles.length; i++) {
            this.addRole(battleRoles[i])
        }
    }

    addRole(battleRole: BattleRole): void {
        let role: BattleRoleUI = this.roleDic[battleRole.uid];
        if (role) return;//重复加入
        role = new BattleRoleUI();
        role.init(battleRole);
        role.setParent(this.UILayer)
        this.roleDic[battleRole.uid] = role;
    }

    addSkillEffect(arg: { spine: Node, pos: { x: number, y: number } }): void {
        let node = arg.spine;
        this.NodeLayer.addChild(node);
        node.setPosition(arg.pos.x, arg.pos.y);
        console.log("添加特效")
    }

    /**飘字 */
    floatTxt(data: { targetUI: BattleRoleUI, txt: string, color: Color }): void {
        let txt = instantiate(this.floatTxtPrefab);
        let label = txt.getComponentInChildren(Label);
        if (label) {
            label.string = data.txt;
        }
        this.NodeLayer.addChild(txt);
        txt.setPosition(new Vec3(data.targetUI.position.x, data.targetUI.position.y + 200, 0));
        let color = data.color ? data.color : Color.WHITE;
        label.color = color;
        tween(txt)
            .to(0.2, { position: new Vec3(txt.position.x, txt.position.y + 100, 0) })
            .to(0.5, {}, {
                onComplete: (target: Node) => {
                    target.removeFromParent();
                }
            })
            .start()
    }
}


